﻿$(function () {
    layui.use(['layer', 'element', 'form', 'upload'], function () {
        var layer = layui.layer,
            element = layui.element,
            form = layui.form,
            upload = layui.upload;

        //创建监听函数
        var xhrOnProgress = function (fun) {
            xhrOnProgress.onprogress = fun; //绑定监听
            //使用闭包实现监听绑
            return function () {
                //通过$.ajaxSettings.xhr();获得XMLHttpRequest对象
                var xhr = $.ajaxSettings.xhr();
                //判断监听函数是否为函数
                if (typeof xhrOnProgress.onprogress !== 'function')
                    return xhr;
                //如果有监听函数并且xhr对象支持绑定时就把监听函数绑定上去
                if (xhrOnProgress.onprogress && xhr.upload) {
                    xhr.upload.onprogress = xhrOnProgress.onprogress;
                }
                return xhr;
            }
        }

        var uploadFile = upload.render({
            elem: '#uploadAudio', //绑定元素
            url: 'http://www.wwfeng.cn:8080/wceManage/common/upload', //上传接口
            exts: 'mp3|aac|ape',//限定上传类型
            //accept: images,//指定允许上传时校验的文件类型 images（图片）、file（所有文件）、video（视频）、audio（音频）
            acceptMime: 'audio/mp3, audio/aac, audio/ape',//只筛选上述类型图片
            //number： '0',//0为不限制上传数量
            xhr: xhrOnProgress,
            //监听xhr进度，并返回给进度条
            progress: function (value) { //上传进度回调 value进度值
                element.progress('uploadAudio_progress', value + '%') //设置页面进度条
            },
            before: function (obj) {
                //开始上传时候让进度条去除隐藏状态
                $("#uploadAudio_progress").removeClass("layui-hide");
            },

            done: function (res, index, upload) {
                $("#audioUrl").val(res.msg);
                $("#uploadAudio_preview").html("<audio src='" + res.msg + "' width='500' controls='controls' />");
            },
            error: function (index, upload) {
                //请求异常回调
                layer.close(layer.index);
                layer.confirm("上传失败，您是否要重新上传？", {
                    btn: ['确定', '取消'],
                    icon: 3,
                    title: "提示"
                }, function () {
                    //关闭询问框
                    layer.closeAll();
                    //重新调用上传方法
                    uploadFile.upload();
                })
            }
        });
    })
})